package cn.fl.repay.service.impl;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.api.IProjectQueryApiService;
import cn.fl.project.condition.PrjBscInfoQueryCondition;
import cn.fl.project.condition.PrjPrdPaySchMQueryCondition;
import cn.fl.project.dto.PrjBscInfoDTO;
import cn.fl.project.dto.PrjPrdPaySchMDTO;
import cn.fl.project.service.IPrjPrdPaySchMApiService;
import cn.fl.repay.dto.InsCstRepaySettleDTO;
import cn.fl.repay.service.IInsCstRepaySettleService;
import cn.fl.repay.service.api.IInsCstRepaySettleApiService;
import cn.fl.repay.transform.InsCstRepaySettleVOTransform;
import cn.fl.repay.vo.InsCstRepaySettleVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pam.transmissionrec.facade.api.ITransLogApiService;
import pam.transmissionrec.facade.condition.InfTransLogExtQueryCondition;
import pam.transmissionrec.facade.dto.InfTransLogDTO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class InsCstRepaySettleServiceImpl implements IInsCstRepaySettleService {

    @Autowired
    private IPrjPrdPaySchMApiService prjPrdPaySchMApiService;
    @Autowired
    private IProjectQueryApiService projectQueryApiService;
    @Autowired
    private IInsCstRepaySettleApiService insCstRepaySettleApiService;
    @Autowired
    private ITransLogApiService transLogApiService;

    /**
     * 分页查询所有
     *
     * @param page
     * @return
     */
    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        page = this.prjPrdPaySchMApiService.searchPrjPrdPaySchMListPage(page, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
        if (null != page && CollectionUtils.isNotEmpty(page.getResultList())) {
            List<Long> prjIdList = new ArrayList<>();
            List<PrjPrdPaySchMDTO> list = (List<PrjPrdPaySchMDTO>) page.getResultList();
            for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : list) {
                prjIdList.add(prjPrdPaySchMDTO.getPrjId());
            }
            PrjBscInfoQueryCondition prjBscInfoQueryCondition = new PrjBscInfoQueryCondition();
            prjBscInfoQueryCondition.setIdList(prjIdList);
            prjBscInfoQueryCondition.setIsDel(0);
            List<PrjBscInfoDTO> prjBscInfoDTOList = projectQueryApiService.searchPrjBscInfoList(prjBscInfoQueryCondition);
            Map<Long, PrjBscInfoDTO> prjBscInfoDTOMap = new HashMap<>();
            for (PrjBscInfoDTO prjBscInfoDTO : prjBscInfoDTOList) {
                prjBscInfoDTOMap.put(prjBscInfoDTO.getId(), prjBscInfoDTO);
            }

            List<InsCstRepaySettleVO> voList = new ArrayList<>();
            if (CollectionUtils.isMapNotEmpty(prjBscInfoDTOMap)) {
                InsCstRepaySettleVO vo = null;
                for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : list) {
                    vo = new InsCstRepaySettleVO();
                    vo.setId(prjPrdPaySchMDTO.getId());
                    vo.setPaySchNo(prjPrdPaySchMDTO.getPaySchNo());
                    vo.setCstId(prjPrdPaySchMDTO.getCstId());
                    vo.setPrjId(prjPrdPaySchMDTO.getPrjId());
                    vo.setLsDt(prjPrdPaySchMDTO.getLsDt());
                    if (prjBscInfoDTOMap.containsKey(prjPrdPaySchMDTO.getPrjId())) {
                        PrjBscInfoDTO prjBscInfoDTO = prjBscInfoDTOMap.get(prjPrdPaySchMDTO.getPrjId());
                        vo.setLsCntNo(prjBscInfoDTO.getLsCntNo());
                        vo.setCstNm(prjBscInfoDTO.getCstNm());
                        vo.setInsCode(prjBscInfoDTO.getInsCode());
                        vo.setInsId(prjBscInfoDTO.getFundRasInsId());
                        vo.setInsNm(prjBscInfoDTO.getFundRasInsNm());
                    }
                    voList.add(vo);
                }
            }
            page.setResultList(voList);
        }
        return page;
    }

    /**
     * 提前还款（结清）试算
     *
     * @param vo
     * @throws BaseException
     */
    @Override
    public DataResultVO searchSettleInfo(InsCstRepaySettleVO vo) throws BaseException {
        DataResultDTO resultDTO = insCstRepaySettleApiService.searchSettleInfo(InsCstRepaySettleVOTransform.toDTO(vo));
        if (resultDTO != null) {
            if(resultDTO.getSuccess() == 1){
                InsCstRepaySettleDTO dto = (InsCstRepaySettleDTO) resultDTO.getData();
                if(null != dto){
                    if(null!=dto.getLsCapAmt()){
                        vo.setLsCapAmt(dto.getLsCapAmt());
                    }
                    if(null!=dto.getLsArCapAmt()){
                        vo.setLsArCapAmt(dto.getLsArCapAmt());
                    }
                    if(null!=dto.getRepayCapAmt()) {
                        vo.setRepayCapAmt(dto.getRepayCapAmt());
                    }
                    if(null!=dto.getRepayIntrAmt()) {
                        vo.setRepayIntrAmt(dto.getRepayIntrAmt());
                    }
                    if(null!=dto.getRepaySvcFeeAmt()) {
                        vo.setRepaySvcFeeAmt(dto.getRepaySvcFeeAmt());
                    }
                    if(null!=dto.getRepayTtlAmt()) {
                        vo.setRepayTtlAmt(dto.getRepayTtlAmt());
                    }


                    if(null!=dto.getExpPrinAmt()) {
                        vo.setExpPrinAmt(dto.getExpPrinAmt());
                    }

                    if(null!=dto.getExpIntAmt()) {
                        vo.setExpIntAmt(dto.getExpIntAmt());
                    }
                    if(null!=dto.getExpFeeAmt()) {
                        vo.setExpFeeAmt(dto.getExpFeeAmt());
                    }

                    if(null!=dto.getOdPenltyAmt()) {
                        vo.setOdPenltyAmt(dto.getOdPenltyAmt());
                    }
                    if(null!=dto.getOdCompdInt()) {
                        vo.setOdCompdInt(dto.getOdCompdInt());
                    }

                    if(null!=dto.getDefltAmt()) {
                        vo.setDefltAmt(dto.getDefltAmt());
                    }
                    if(null!=dto.getOvrpdAmt()) {
                        vo.setOvrpdAmt(dto.getOvrpdAmt());
                    }

                }
                return new DataResultVO(BaseConstant.IS_YESNO_YES,"查询成功",vo);
            }
            return new DataResultVO(resultDTO.getSuccess(),resultDTO.getInfo());
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"查询三方接口异常");
        }
    }

    /**
     * 提前还款（结清）
     *
     * @param vo
     * @throws BaseException
     */
    @Override
    public DataResultVO settle(InsCstRepaySettleVO vo) throws BaseException {
        DataResultDTO resultDTO = insCstRepaySettleApiService.settle(InsCstRepaySettleVOTransform.toDTO(vo));
        if (resultDTO != null) {
            return new DataResultVO(resultDTO.getSuccess(),resultDTO.getInfo(),vo);
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"查询三方接口异常");
        }
    }

    /**
     * 欠款查询（代偿试算）
     *
     * @param vo
     * @return DataResultDTO
     * @throws BaseException
     */
    @Override
    public DataResultVO searchRepayInfo(InsCstRepaySettleVO vo) throws BaseException {
        DataResultDTO resultDTO = insCstRepaySettleApiService.searchSettleInfo(InsCstRepaySettleVOTransform.toDTO(vo));
        if (resultDTO != null) {
            if(resultDTO.getSuccess() == 1){
                List<InsCstRepaySettleDTO> dtoList = (List<InsCstRepaySettleDTO>) resultDTO.getData();
                //拼装欠款明细列表
                Map<String,List<InsCstRepaySettleDTO>> map = new HashMap<>();
                if(CollectionUtils.isNotEmpty(dtoList)){
                    map.put("rows",dtoList);
                }
                return new DataResultVO(BaseConstant.IS_YESNO_YES,"查询成功",JSON.toJSONString(map));
            }
            return new DataResultVO(resultDTO.getSuccess(),resultDTO.getInfo());
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"查询三方接口异常");
        }
    }

    /**
     * 贷款还款（代偿）
     *
     * @param vo
     * @return DataResultDTO
     * @throws BaseException
     */
    @Override
    public DataResultVO repay(InsCstRepaySettleVO vo) throws BaseException {
        DataResultDTO resultDTO = insCstRepaySettleApiService.repay(InsCstRepaySettleVOTransform.toDTO(vo));
        if (resultDTO != null) {
            return new DataResultVO(resultDTO.getSuccess(),resultDTO.getInfo(),vo);
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"查询三方接口异常");
        }
    }

    /**
     * 查询代偿记录日志列表
     *
     * @param page
     * @return
     * @throws BaseException
     */
    @Override
    public Pager searchRepayLogListPage(Pager page) throws BaseException {
        InfTransLogExtQueryCondition qc = (InfTransLogExtQueryCondition) page.getCondition();
        PrjPrdPaySchMQueryCondition paySchMQueryCondition = new PrjPrdPaySchMQueryCondition();
        List<PrjPrdPaySchMDTO> prdPaySchMDTOList = null;
        PrjPrdPaySchMDTO paySchMDTO = null;
        paySchMQueryCondition.setPaySchTypCd("ZF");
        paySchMQueryCondition.setIsSqBiz(0);
        if (StringUtils.isNotBlank(qc.getPaySchNo())) {
            paySchMQueryCondition.setPaySchNo(qc.getPaySchNo());
            prdPaySchMDTOList = this.prjPrdPaySchMApiService.searchPrjPrdPaySchMList(paySchMQueryCondition);
            if (CollectionUtils.isNotEmpty(prdPaySchMDTOList)) {
                paySchMDTO = prdPaySchMDTOList.get(0);
                qc.setPrjId(paySchMDTO.getPrjId());
                qc.setPaySchNo(null);
            } else {
                return page;
            }
            paySchMQueryCondition.setPaySchNo(null);
        }
        BaseLogUtils.newLogger("查询代偿记录日志列表开始").setKeys(JSON.toJSONString(page)).info();
        try {
            page = this.transLogApiService.selectListByPager(page);
            BaseLogUtils.newLogger("查询代偿记录日志列表结束").setKeys(JSON.toJSONString(page)).info();
        } catch (Exception e) {
            BaseLogUtils.newLogger("查询代偿记录日志列表异常").setKeys(JSON.toJSONString(page)).setThrowable(e).error(LogExceptionEnum.API_CODE_0199);
        }
        if (page != null && CollectionUtils.isNotEmpty(page.getResultList())) {
            List<InfTransLogDTO> transLogDTOList = (List<InfTransLogDTO>) page.getResultList();
            Map<Long, PrjPrdPaySchMDTO> paySchMDTOMap = new HashMap<>();
            if (null != paySchMDTO) {
                paySchMDTOMap.put(paySchMDTO.getPrjId(), paySchMDTO);
            } else {
                List<Long> prjIdList = new ArrayList<>();
                for (InfTransLogDTO infTransLogDTO : transLogDTOList) {
                    if (StringUtils.isNotEmpty(infTransLogDTO.getPrjId())) {
                        prjIdList.add(infTransLogDTO.getPrjId());
                    }
                }
                if (CollectionUtils.isNotEmpty(prjIdList)) {
                    paySchMQueryCondition.setPrjIdList(prjIdList);
                    prdPaySchMDTOList = this.prjPrdPaySchMApiService.searchPrjPrdPaySchMList(paySchMQueryCondition);
                    for (PrjPrdPaySchMDTO prjPrdPaySchMDTO : prdPaySchMDTOList) {
                        paySchMDTOMap.put(prjPrdPaySchMDTO.getPrjId(), prjPrdPaySchMDTO);
                    }
                }
            }
            InsCstRepaySettleVO vo = null;
            List<InsCstRepaySettleVO> voList = new ArrayList<>();
            for (InfTransLogDTO infTransLogDTO : transLogDTOList) {
                vo = new InsCstRepaySettleVO();
                vo.setInsCode(infTransLogDTO.getFundRasInsNo());
                vo.setPrjId(infTransLogDTO.getPrjId());
                vo.setCstNm(infTransLogDTO.getCstNm());
                vo.setPaySchNo(infTransLogDTO.getPaySchNo());
                if ("pass".equals(infTransLogDTO.getRemark())) {
                    vo.setStatus("已通过");
                } else if ("reject".equals(infTransLogDTO.getRemark())) {
                    vo.setStatus("已拒绝");
                } else {
                    vo.setStatus("处理中");
                }
                if("zbbank".equals(infTransLogDTO.getFundRasInsNo())){
                    if("OSFS100000".equals(infTransLogDTO.getRespCode())){
                        vo.setStatus("已通过");
                    } else if ("OSFS200000".equals(infTransLogDTO.getRespCode())) {
                        vo.setStatus("已拒绝");
                    } else {
                        vo.setStatus("处理中");
                    }
                }
                if("tyfl".equals(infTransLogDTO.getFundRasInsNo())){
                    if ("pass".equals(infTransLogDTO.getRespCode())) {
                        vo.setStatus("已通过");
                    } else if ("reject".equals(infTransLogDTO.getRespCode())) {
                        vo.setStatus("已拒绝");
                    } else {
                        vo.setStatus("处理中");
                    }
                }
                if("spdbank".equals(infTransLogDTO.getFundRasInsNo())){
                    if("success".equals(infTransLogDTO.getStatus())){
                        vo.setStatus("已通过");
                    } else if ("failure".equals(infTransLogDTO.getStatus())) {
                        vo.setStatus("已拒绝");
                    } else {
                        vo.setStatus("处理中");
                    }
                }
                if (paySchMDTOMap.containsKey(infTransLogDTO.getPrjId())) {
                    PrjPrdPaySchMDTO prjPrdPaySchMDTO = paySchMDTOMap.get(infTransLogDTO.getPrjId());
                    vo.setPaySchNo(prjPrdPaySchMDTO.getPaySchNo());
                    vo.setLsCntNo(prjPrdPaySchMDTO.getLsCntNo());
                    vo.setInsNm(prjPrdPaySchMDTO.getFundRasInsNm());
                    vo.setCstNm(prjPrdPaySchMDTO.getCstNm());
                    vo.setLsDt(prjPrdPaySchMDTO.getLsDt());
                }
                voList.add(vo);
            }
            page.setResultList(voList);
        }
        return page;
    }
}
